<?php

require_once 'shared-functions.php';

$schemadir = 'schema';
$schemafile = $schemadir . '/' . 'schooltracking-schema.sql';

/**
 *
 * @return - string: a generated filename for use in backup functions
 * @author - Joshua Clayton
 * @version - 1.0
 */
function gen_backup_sql_filename($bktype)
{
    global $db_database;
    global $db_directory;

    return $db_directory . "/" .
           $db_database . "-" .
           $bktype . "-" .
           date("Y-m-d-Hi") .
           ".sql";
}

/**
 *
 * @return - string: the return value is the output of the mysql command. This should normally be blank unless there was an error
 * @author - Joshua Clayton
 * @version - 1.0
 */
function backup_db_contents($db_admin_username, $db_admin_password, $bk_filename)
{
    global $db_hostname;
    global $db_database;
    global $db_directory;

    $backup_cmd = "mysqldump --no-create-info -h " .  $db_hostname .
                  " -u".$db_admin_username .
                  " -p" . $db_admin_password .
                  " ".$db_database .
                  " > ". $bk_filename." 2>&1";
    return system($backup_cmd);
}

/**
 *
 * @return - string: the return value is the output of the mysql command. This should normally be blank unless there was an error
 * @author - Joshua Clayton
 * @version - 1.0
 */
function backup_db_schema($db_admin_username, $db_admin_password)
{
    global $db_hostname;
    global $db_database;
    global $schemadir;
    global $schemafile;

    $backup_cmd = "mysqldump --no-data -h " .  $db_hostname .
                  " -u".$db_admin_username .
                  " -p" . $db_admin_password .
                  " ".$db_database .
                  " > ". $schemafile." 2>&1";
    return system($backup_cmd);
}

/**
 *
 *WARNING: This function wipes out all the data in the database.
 *It may be used to load a new schema, or simply to empty all tables
 *
 * @return - string: the return value is the output of the mysql command. This should normally be blank unless there was an error
 * @author - Joshua Clayton
 * @version - 1.0
 */
function reload_schema($db_admin_username, $db_admin_password)
{
    global $schemadir;
    global $schemafile;
    return run_db_script($db_admin_username, $db_admin_password, $schemafile);

}

/**
 *
 * @return - string: the return value is the output of the mysql command. This should normally be blank unless there was an error
 * @author - Joshua Clayton
 * @version - 1.0
 */
function run_db_script($db_admin_username,
                       $db_admin_password,
                       $script_file)
{
    global $db_hostname;
    global $db_database;
    $restore_cmd = "mysql -h " . $db_hostname .
                  " -u".$db_admin_username .
                  " -p" . $db_admin_password .
                  " --database=".$db_database .
                  " < ". $script_file." 2>&1";

    return system($restore_cmd);
}
